#include <pthread.h>
#include <unistd.h>
#include "linux.h"

stTimer SysTimer;

void *thread_timer( void *ptr )
{
    SysTimer.InterruptRunning = FALSE;
    while (SysTimer.Enabled == FALSE) {
        usleep(100);
    }
    
    while(1) {
        usleep(100);
        if (SysTimer.Val >= SysTimer.Mod) {

            if (SysTimer.InterruptEnabled == FALSE){
                usleep(100);
                continue;
            }
            
            //SysTimer.InterruptRunning = TRUE;
            Core_PhyTimerInterrupt();
            //SysTimer.InterruptRunning = FALSE;
            
            while (SysTimer.Enabled == FALSE) {
                usleep(100);
            }
        } else {
            SysTimer.Val++;
        }
    }
}

void thread_timer_start(void)
{
    SysTimer.Val = 0;    
    SysTimer.Enabled = TRUE;
    //printf("timer start");
}

void thread_timer_stop(void)
{
    SysTimer.Enabled = FALSE;
    //printf("timer stop");
}


int main(void) {
    pthread_t systimer;
    int tid = pthread_create( &systimer, NULL, &thread_timer, (void *)NULL);
    ENABLE_INTERRUPT;
    Core_Run();
    pthread_join( systimer, NULL);
}

